<template>
  <PageWrapper dense contentFullHeight fixedHeight contentClass="flex">
    <div class="w-1/4 xl:w-1/5 m-2 overflow-hidden bg-white" v-if="isNotQuery == 1">
      <div class="h-full overflow-auto pb-2">
        <FlowTree
          @select="handleSelect"
          @del-action="delAction"
          @ok="onClose"
          ref="treeRef"
          @add-action="addAction"
          @tree-context-menu="treeContextMenu"
          @edit-action="handleEditAction"
          @root-record="handleRootRecord"
        />
      </div>
    </div>
    <div
      class="mt-2 mb-2 bg-white"
      :class="{ 'w-full': isNotQuery != 1, 'w-3/4 xl:w-4/5': isNotQuery == 1 }"
    >
      <Tabs
        v-model:activeKey="activeKey"
        centered
        class="h-full"
        @change="handleTabChange"
        v-if="!isRootNodeShowBySubUnitUser"
      >
        <TabPane
          v-for="item in tabList"
          :key="item.key"
          :tab="item.title"
          class="h-full"
          forceRender
        >
          <component
            :is="item.component"
            :current-record="dataRef"
            :current-key="item.key"
            :active-key="activeKey"
            :form-code="editNodeInfo.formCode"
            @success="handleSuccess"
            :ref="setRefs(item.key)"
            @edit-node="handleEditNode"
          />
        </TabPane>
      </Tabs>
      <Empty v-else :image="simpleImage" description="请选择节点" />
    </div>
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, onMounted, watch } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { Tabs, TabPane, Select, Empty } from 'ant-design-vue';
  import { useRefs } from '/@/hooks/core/useRefs';
  import FlowTree from './modules/flowTree/FlowTree.vue';
  import Attribute from './modules/attribute/Attribute.vue';
  import AttributeAdd from './modules/attribute/Attribute.vue';
  import Authority from './modules/authority/Authority.vue';
  import DisplayRules from './modules/displayRules/DisplayRules.vue';
  import EfficiencyAnalysis from './modules/efficiencyAnalysis/EfficiencyAnalysis.vue';
  import FlowPicture from './modules/flowPicture/FlowPicture.vue';
  import MonthlyStatistics from './modules/monthlyStatistics/MonthlyStatistics.vue';
  import RecordList from './modules/recordList/RecordList.vue';
  import YearStatistics from './modules/yearStatistics/YearStatistics.vue';
  import Config from './modules/config/Config.vue';

  // import { getAdminFlowEditNode } from '/@/api/flowManage/flowManage';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { TabList, DataList, layer1, layer2, layer3, layer4 } from './flowManagement.data';

  import { useGo } from '/@/hooks/web/usePage';
  import { useRouter } from 'vue-router';
  import { useUserStore } from '/@/store/modules/user';
  import { getToken } from '/@/utils/auth';

  export default defineComponent({
    name: 'FlowManagement',
    components: {
      PageWrapper,
      FlowTree,
      Tabs,
      TabPane,
      Select,
      Attribute,
      AttributeAdd,
      Authority,
      DisplayRules,
      EfficiencyAnalysis,
      FlowPicture,
      MonthlyStatistics,
      RecordList,
      YearStatistics,
      Config,
      Empty,
    },
    setup() {
      const [refs, setRefs] = useRefs();
      const treeRef: any = ref(null);
      const rootRecord = ref({}); //顶级对象

      const userStore = useUserStore();
      const userInfo = userStore.getUserInfo;
      const serverInfo = userStore.getServerInfo;
      const isRootNodeShowBySubUnitUser = ref(true);
      const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;

      let dataRef = ref<DataList>({});
      const { createMessage } = useMessage();
      const isNotQuery = ref<string | number>(1); //默认是1 2是从流程统计跳转过来
      const { currentRoute, resolve } = useRouter();
      const fetch = async () => {
        const { query } = unref(currentRoute);
        // 从debug模式点击“管理”进入
        if (query.typeCode) {
          if (query.typeCode != 'root') {
            isRootNodeShowBySubUnitUser.value = false;
          } else {
            isRootNodeShowBySubUnitUser.value = userInfo['unitCode'] != 'root';
          }
        }

        if (query.isNotQuery) {
          isNotQuery.value = query.isNotQuery as string;
          console.log('query', query);
          const params = {
            code: query.typeCode,
            name: query.typeName,
            layer: query.layer,
          };
          setTabs(params);
          setTimeout(() => {
            activeKey.value = query.type as string;
          }, 30);
          // const data = await getAdminFlowEditNode({ code: query.typeCode });
          // handleEditNode(data);
        }
      };
      onMounted(fetch);

      function onClose(e?: number) {
        if (e != 1) {
          //1是新增，不用清空
          dataRef.value = {};
        }
      }
      const activeKey = ref<string | number>('Attribute');
      const oldActiveKey = ref<string | number>('');
      watch(
        activeKey,
        () => {
          if (activeKey.value != 'FormCode' && activeKey.value != 'RecordList') {
            oldActiveKey.value = activeKey.value;
          }
        },
        {
          immediate: true,
        },
      );
      const tabList = ref<TabList[]>([]);

      tabList.value = layer1;
      //树新增事件
      const addAction = () => {
        activeKey.value = 'AttributeAdd';
        refs.value['AttributeAdd'].initData();
      };

      //树删除事件
      const delAction = () => {
        if (!dataRef.value.code) {
          createMessage.warning('请选择节点');
          return;
        }
        unref(treeRef)?.setMenuDelete(dataRef.value.code);
        onClose();
      };

      const handleSelect = (_, trc) => {
        const data = trc.node.dataRef;
        console.log('handleSelect data', data);
        if (data.code != 'root') {
          isRootNodeShowBySubUnitUser.value = false;
        } else {
          isRootNodeShowBySubUnitUser.value = userInfo['unitCode'] != 'root';
        }
        setTabs(data);
      };
      //右击选择
      const treeContextMenu = (record) => {
        setTabs(record);
      };

      const setTabs = (record) => {
        dataRef.value = record;
        console.log('setTabs', unref(dataRef));
        const { layer } = record;
        if (layer == 1) {
          tabList.value = layer1;
        } else if (layer == 2) {
          tabList.value = layer2;
        } else if (layer == 3) {
          if (unref(dataRef)?.type == 1) {
            //自由流程
            tabList.value = layer4;
          } else {
            tabList.value = layer3;
          }

          // 如果是标准版或小菜版
          if (
            serverInfo.versionType &&
            (serverInfo.versionType == 'Standard' || serverInfo.versionType == '0')
          ) {
            tabList.value = tabList.value.filter((el) => el.key !== 'DisplayRules');
          }
        }

        if (!serverInfo.isViewRuleEnabled) {
          tabList.value = tabList.value.filter((el) => el.key !== 'DisplayRules');
        }

        activeKey.value = tabList.value[0].key;
        setTimeout(() => {
          refs.value['Attribute']?.initData();
        }, 10);
      };
      //成功回调
      const handleSuccess = (type) => {
        treeRef.value.fetch(true);
        if (type == 'add') {
          activeKey.value = tabList.value[0].key;
        }
      };
      //编辑节点
      const handleEditAction = () => {
        activeKey.value = 'Attribute';
      };
      //获取顶级code
      const handleRootRecord = (record) => {
        rootRecord.value = record;
        if (rootRecord.value == 'root') {
          isRootNodeShowBySubUnitUser.value = userInfo['unitCode'] != 'root';
        }
      };
      //编辑回调存储信息
      const editNodeInfo = ref<any>({});
      const handleEditNode = (record) => {
        editNodeInfo.value = record;
      };

      const go = useGo();
      //切换tab
      const handleTabChange = (val) => {
        if (val == 'FormCode') {
          // go({
          //   path: '/formEdit',
          //   query: {
          //     urlParams: '/admin/form_edit.jsp?code=' + editNodeInfo.value?.formCode,
          //   },
          // });

          let routeUrl: any = {};
          routeUrl = resolve({
            path: '/formEditor',
            query: {
              formCode: editNodeInfo.value?.formCode,
              pageName: currentRoute.value.meta.title,
              // name: formRowData.value.cwsWorkflowTitle,
              token: getToken() as any,
            },
          });
          const height = screen.height;
          const width = screen.width;
          window.open(
            routeUrl.href,
            '',
            `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
          );

          activeKey.value = oldActiveKey.value;
        } else if (val == 'RecordList') {
          go({
            path: '/flowRecord',
            query: {
              tabName: unref(dataRef)?.name,
              typeCode: unref(dataRef).code,
              formCode: unref(editNodeInfo).formCode,
            },
          });
          activeKey.value = oldActiveKey.value;
        } else if (val == 'AttributeAdd') {
          addAction();
        }
      };
      return {
        handleSelect,
        treeRef,
        addAction,
        delAction,
        onClose,
        treeContextMenu,
        tabList,
        activeKey,
        dataRef,
        handleSuccess,
        setRefs,
        handleEditAction,
        handleRootRecord,
        handleEditNode,
        handleTabChange,
        editNodeInfo,
        isNotQuery,
        isRootNodeShowBySubUnitUser,
        simpleImage,
      };
    },
  });
</script>
<style lang="less" scoped>
  :deep(.ant-card-head) {
    min-height: 37px;
  }
  :deep(.ant-card-head-title) {
    padding: 0;
    line-height: 35px;
  }

  :deep(.ant-tabs-content) {
    height: 100%;
  }
</style>
